<template>
  <div>
    <a-space style="margin: 15px 0" wrap>
      <TableHeaderButton :TableHeaderButton="tableHeaderButton" :exportFunction="exportFunction"
                         :openModel="openModel" @changeStatus="changeStatus"></TableHeaderButton>
    </a-space>
    <a-table
        ref="TableRef"
        :columns="prop.columns"
        :customRow="rowClick"
        :data-source="prop.data"
        :row-selection="rowSelection"
        style="height: calc(100vh - 280px)"
    >
      <template #bodyCell="{column,value}">
        <template v-if="column.key === 'action'">
          <TableButton :ButtonList="column.btn" :openModel="openModel" :value="value"
                       @changeStatus="changeStatus" @refresh="refresh"></TableButton>
        </template>
      </template>
    </a-table>
    <Model ref="ModelRef" :title="title">
      <slot></slot>
    </Model>
  </div>
</template>
<script setup>
import Model from "@/components/Modal/index.vue";
import TableButton from "@/components/TableButton/index.vue";
import TableHeaderButton from "@/components/TableHeaderButton/index.vue";
import {ref} from "vue";
import * as XLSX from "xlsx";
import eventBus from "@/utils/eventBus.js";

const TableRef = ref('')
const ModelRef = ref("");
let title = ref("");
let statusType = ref('add')
let editId = ref({})
let FormData = defineModel('formState')
let prop = defineProps({
  columns: {
    type: Array,
    default: [],
  },
  tableHeaderButton: {
    type: Array,
    default: [],
  },
  data: {
    type: Array,
    default: [],
  },
  refresh: {
    type: Function,
    default: () => {
    },
  },
  resetForm: {
    type: Function,
    default: () => {
    }
  },
});

// 点击开启Model
const openModel = (tag, type = '', data = {}) => {
  if (type === 'edit') FormData.value = data
  title.value = tag;
  ModelRef.value.ToggleModal();
};
// 关闭Model
const closeModel = () => {
  ModelRef.value.ToggleModal(prop.resetForm);
}
// 更新数据
const refresh = async () => {
  await prop.refresh();
}
// 导出excel
const exportFunction = () => {
  if (!TableRef.value) return
  const wb = XLSX.utils.table_to_book(TableRef.value);
  XLSX.writeFile(wb, '表格数据.xlsx');
}

// 更新form状态
const changeStatus = (type, data) => {
  statusType.value = type;
  if (type === 'edit') editId.value = data
}
defineExpose({
  closeModel,
  statusType,
  editId
})

// 每行点击事件
function rowClick(record) {
  return {
    onclick: () => {
      eventBus.emit('rowClick', record)
    }
  }
}


const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
    );
  },
};
</script>

<style lang="scss" scoped>

</style>